<template>
  <div class="create-post-container">
    <!-- 顶部导航区 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <a-button class="back-btn" @click="handleCancel">
            <template #icon><arrow-left-outlined /></template>
            返回
          </a-button>
          <h1>创建新帖子</h1>
        </div>
        <div class="header-right">
          <a-space>
            <a-button type="primary" @click="handleSubmit" :loading="submitting">
              <template #icon><send-outlined /></template>
              发布并提交审核
            </a-button>
          </a-space>
        </div>
      </div>
      <!-- 审核提示 -->
      <a-alert
        class="audit-alert"
        message="内容审核提示"
        description="您发布的所有帖子都将经过审核，审核通过后将对其他用户可见。请确保内容符合社区规范。"
        type="info"
        show-icon
      />
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 左侧编辑区 -->
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        class="edit-section"
      >
        <!-- 标题输入 -->
        <a-form-item name="title">
          <div class="title-input-wrapper">
            <a-input
              v-model:value="formState.title"
              placeholder="请输入帖子标题..."
              :maxLength="100"
              :bordered="false"
              class="title-input"
            />
            <div class="title-counter">{{ formState.title.length }}/100</div>
          </div>
        </a-form-item>

        <!-- Markdown编辑器 -->
        <a-form-item name="content">
          <div class="editor-wrapper">
            <md-editor
              v-model="formState.content"
              @onChange="handleEditorChange"
              :toolbars="toolbars"
              :height="500"
            />
          </div>
        </a-form-item>

        <!-- 摘要输入 -->
        <a-form-item name="summary">
          <div class="summary-wrapper">
            <div class="summary-header">
              <h3>
                <align-left-outlined />
                文章摘要
              </h3>
              <a-switch
                v-model:checked="autoGenerateSummary"
                size="small"
                :checked-children="'自动'"
                :un-checked-children="'手动'"
              />
            </div>
            <a-textarea
              v-model:value="formState.summary"
              placeholder="请输入帖子摘要，或启用自动摘要提取功能"
              :maxLength="200"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              show-count
              @change="handleSummaryChange"
            />
            <div class="summary-tip" v-if="autoGenerateSummary">
              <info-circle-outlined /> 自动摘要模式已开启，将根据文章内容自动提取摘要
            </div>
          </div>
        </a-form-item>
      </a-form>

      <!-- 右侧配置区 -->
      <div class="config-section">
        <!-- 发布设置卡片 -->
        <div class="config-card">
          <div class="card-header">
            <setting-outlined />
            <span>发布设置</span>
          </div>
          <div class="card-content">
            <!-- 封面图上传 -->
            <div class="upload-section">
              <div class="section-title">封面图片</div>
              <a-form-item name="coverImage">
                <a-upload
                  v-model:file-list="fileList"
                  list-type="picture-card"
                  :max-count="1"
                  :before-upload="beforeUpload"
                  @preview="handlePreview"
                  :customRequest="handleUpload"
                  @change="handleUploadChange"
                  class="cover-uploader"
                >
                  <div v-if="fileList.length < 1">
                    <div class="upload-hint">
                      <picture-outlined />
                      <p>点击上传封面</p>
                      <span>支持 jpg/png 格式，小于2MB</span>
                    </div>
                  </div>
                </a-upload>
                <div v-if="uploadStatus === 'uploading'" class="upload-status uploading">
                  <loading-outlined spin /> 图片上传中...
                </div>
                <div v-if="uploadStatus === 'error'" class="upload-status error">
                  <exclamation-circle-outlined /> 上传失败: {{ uploadError }}
                  <a @click="uploadStatus = 'idle'">关闭</a>
                </div>
                <div v-if="uploadStatus === 'success'" class="upload-status success">
                  <check-circle-outlined /> 上传成功
                </div>
                <div class="upload-tip">
                  <info-circle-outlined /> 推荐尺寸: 900x300像素，保持16:9比例
                </div>
              </a-form-item>
            </div>

            <!-- 分类选择 -->
            <div class="category-section">
              <div class="section-title">文章分类</div>
              <a-form-item name="categoryId">
                <a-select
                  v-model:value="formState.categoryId"
                  placeholder="请选择分类"
                  :options="categories"
                  :loading="categoriesLoading"
                  class="category-select"
                />
              </a-form-item>
            </div>

            <!-- 标签选择 -->
            <div class="tags-section">
              <div class="section-title">文章标签</div>
              <a-form-item name="tags">
                <a-select
                  v-model:value="formState.tags"
                  mode="tags"
                  placeholder="请输入标签，按回车确认"
                  :options="tagOptions"
                  :loading="tagsLoading"
                  class="tags-select"
                />
                <div class="tags-hint">最多可添加5个标签</div>
              </a-form-item>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预览模态框 -->
    <a-modal
      :open="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handlePreviewCancel"
    >
      <img alt="preview" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'
import { 
  PlusOutlined, 
  ArrowLeftOutlined, 
  SaveOutlined, 
  SendOutlined, 
  SettingOutlined, 
  AlignLeftOutlined, 
  PictureOutlined,
  InfoCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons-vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import type { UploadProps, FormInstance } from 'ant-design-vue'
import { createPost, uploadImage, getCategories, getTags } from '@/api/post'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref<FormInstance>()

// 表单状态
const formState = reactive({
  title: '',
  categoryId: undefined as number | undefined,
  content: '',
  summary: '',
  coverImage: '',
  tags: [] as string[],
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2-100个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, message: '内容至少10个字符', trigger: 'blur' }
  ],
  summary: [
    { max: 200, message: '摘要不能超过200个字符', trigger: 'blur' }
  ],
  tags: [
    { 
      validator: async (rule: any, value: string[]) => {
        if (value && value.length > 5) {
          throw new Error('最多只能添加5个标签')
        }
      },
      trigger: 'change'
    }
  ]
}

// 分类数据
const categories = ref<{ value: number; label: string; }[]>([])
const categoriesLoading = ref(false)

// 标签数据
const tagOptions = ref<{ value: string; label: string; }[]>([])
const tagsLoading = ref(false)

// 上传相关
const fileList = ref<any[]>([])
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const uploadStatus = ref('idle')
const uploadError = ref('')

// 编辑器配置
const toolbars = [
  'bold', 'italic', 'strikethrough', 'title', 'sub', 'sup', 'quote', 'unordered-list',
  'ordered-list', 'task-list', 'code', 'code-block', 'table', 'link', 'image',
  'clear', 'preview', 'fullscreen'
] as const

// 加载分类数据
const loadCategories = async () => {
  try {
    categoriesLoading.value = true
    const response = await getCategories()
    categories.value = response.data.map(item => ({
      value: item.id,
      label: item.name
    }))
  } catch (error) {
    console.error('获取分类失败:', error)
    message.error('获取分类失败')
  } finally {
    categoriesLoading.value = false
  }
}

// 加载标签数据
const loadTags = async () => {
  try {
    tagsLoading.value = true
    const response = await getTags()
    tagOptions.value = response.data.map(item => ({
      value: item.name,
      label: item.name
    }))
  } catch (error) {
    console.error('获取标签失败:', error)
    message.error('获取标签失败')
  } finally {
    tagsLoading.value = false
  }
}

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

// 处理图片预览
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

// 处理预览取消
const handlePreviewCancel = () => {
  previewVisible.value = false
}

// 处理编辑器变化
const autoGenerateSummary = ref(true); // 是否自动生成摘要的标志

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return function(this: any, ...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 提取摘要的函数
const extractSummary = (content: string) => {
  if (!autoGenerateSummary.value) return;
  
  // 从Markdown中提取纯文本
  const plainText = content.replace(/#+\s+/g, '')  // 移除标题标记
                         .replace(/\*\*|\*/g, '') // 移除加粗和斜体标记
                         .replace(/\[.*?\]\(.*?\)/g, '$1') // 提取链接文本
                         .replace(/!\[.*?\]\(.*?\)/g, '') // 移除图片
                         .replace(/`{1,3}.*?`{1,3}/g, '') // 移除代码块
                         .replace(/\n/g, ' ') // 换行替换为空格
                         .replace(/\s+/g, ' ') // 多个空格替换为一个
                         .trim(); // 移除首尾空格
  
  formState.summary = plainText.substring(0, 200); // 截取前200个字符
};

// 使用防抖包装摘要提取函数
const debouncedExtractSummary = debounce(extractSummary, 500);

// 处理编辑器变化
const handleEditorChange = (content: string) => {
  formState.content = content;
  // 使用防抖处理的摘要提取
  debouncedExtractSummary(content);
}

// 处理摘要手动编辑
const handleSummaryChange = (e: Event) => {
  // 当用户手动编辑摘要时，关闭自动生成
  autoGenerateSummary.value = false;
}

// 提交表单
const submitting = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 检查用户登录状态
    if (!userStore.userInfo) {
      message.error('请先登录')
      router.push('/login')
      return
    }

    // 准备帖子数据
    const postData = {
      userId: userStore.userInfo.id,
      title: formState.title,
      categoryId: formState.categoryId as number,
      content: formState.content,
      summary: formState.summary,
      coverImage: formState.coverImage, // 使用已上传的封面URL
      tags: formState.tags
    }
    
    // 提交帖子
    const response = await createPost(postData)
    if (response.code === 200) {
      message.success('发布成功，帖子将在审核后显示')
      router.push('/')
    } else {
      throw new Error(response.message || '发布失败')
    }
  } catch (error: any) {
    console.error('发布失败:', error)
    message.error(error.message || '发布失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 取消发布
const handleCancel = () => {
  router.back()
}

// 工具函数：将文件转换为base64
const getBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

// 自定义上传处理
const handleUpload = async (options: any) => {
  const { file, onSuccess, onError, onProgress } = options;
  
  // 检查文件是否符合要求
  if (!beforeUpload(file)) {
    return;
  }
  
  uploadStatus.value = 'uploading';
  
  // 创建FormData
  const formData = new FormData();
  formData.append('file', file);
  
  try {
    // 上传文件
    const result = await uploadImage(formData);
    
    if (result.code === 200) {
      // 上传成功
      formState.coverImage = result.data;
      uploadStatus.value = 'success';
      onSuccess(result, file);
      
      // 3秒后隐藏成功提示
      setTimeout(() => {
        if (uploadStatus.value === 'success') {
          uploadStatus.value = 'idle';
        }
      }, 3000);
      
    } else {
      // 业务逻辑错误
      uploadError.value = result.message || '上传失败';
      uploadStatus.value = 'error';
      onError(new Error(uploadError.value));
    }
  } catch (error: any) {
    // 请求错误
    uploadError.value = error.message || '上传过程中发生错误';
    uploadStatus.value = 'error';
    onError(error);
  }
};

// 处理上传状态变化
const handleUploadChange = (info: any) => {
  // 文件列表变化时记录当前状态
  fileList.value = info.fileList;
  
  // 根据上传状态展示不同的UI
  if (info.file.status === 'uploading') {
    uploadStatus.value = 'uploading';
  } else if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 200) {
      uploadStatus.value = 'success';
    } else {
      uploadStatus.value = 'error';
      uploadError.value = (info.file.response && info.file.response.message) || '上传失败';
    }
  } else if (info.file.status === 'error') {
    uploadStatus.value = 'error';
    uploadError.value = '文件上传失败';
  }
};

// 生命周期钩子
onMounted(() => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    message.warning('请先登录')
    router.push('/login?redirect=/create-post')
    return
  }
  
  // 加载分类和标签数据
  loadCategories()
  loadTags()
})
</script>

<style lang="scss" scoped>
.create-post-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 24px;

  .page-header {
    position: sticky;
    top: 0;
    z-index: 100;
    background: #fff;
    padding: 16px 24px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    margin-bottom: 24px;

    .header-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;

        .back-btn {
          border: none;
          background: transparent;
          color: #8c8c8c;
          transition: all 0.3s ease;

          &:hover {
            color: #1890ff;
            transform: translateX(-2px);
          }
        }

        h1 {
          margin: 0;
          font-size: 22px;
          font-weight: 600;
          background: linear-gradient(45deg, #1890ff, #40a9ff);
          -webkit-background-clip: text;
          color: transparent;
        }
      }

      .header-right {
        .ant-btn {
          height: 36px;
          padding: 0 20px;
          border-radius: 8px;
          font-weight: 500;
          transition: all 0.3s ease;

          &:not(:last-child) {
            margin-right: 12px;
          }

          &.ant-btn-primary {
            background: linear-gradient(45deg, #1890ff, #40a9ff);
            border: none;
            box-shadow: 0 2px 6px rgba(24, 144, 255, 0.35);

            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(24, 144, 255, 0.45);
            }
          }

          .anticon {
            margin-right: 8px;
          }
        }
      }
    }

    .audit-alert {
      margin-bottom: 16px;
    }
  }

  .main-content {
    max-width: 1400px;
    margin: 24px auto;
    display: flex;
    gap: 32px;

    .edit-section {
      flex: 1;
      min-width: 0;
      max-width: calc(100% - 392px);

      .title-input-wrapper {
        margin-bottom: 24px;
        background: #fff;
        border-radius: 12px;
        padding: 24px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

        .title-input {
          font-size: 24px;
          font-weight: 500;
          border: none;
          padding: 0;
          height: auto;
          
          &::placeholder {
            color: #bfbfbf;
          }

          &:focus {
            box-shadow: none;
          }
        }

        .title-counter {
          margin-top: 8px;
          text-align: right;
          color: #8c8c8c;
          font-size: 13px;
        }
      }

      .editor-wrapper {
        margin-bottom: 24px;
        background: #fff;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

        :deep(.md-editor) {
          border: none;
        }
      }

      .summary-wrapper {
        background: #fff;
        border-radius: 12px;
        padding: 24px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

        .summary-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 16px;

          h3 {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
            font-weight: 600;
            color: #262626;
            margin: 0;

            .anticon {
              color: #1890ff;
              font-size: 18px;
            }
          }
          
          .ant-switch {
            background-color: #d9d9d9;
            
            &.ant-switch-checked {
              background-color: #1890ff;
            }
          }
        }

        .ant-textarea {
          border-radius: 8px;
          resize: none;
          font-size: 14px;
          
          &:hover, &:focus {
            border-color: #40a9ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
          }
        }

        .summary-tip {
          margin-top: 8px;
          font-size: 12px;
          color: #8c8c8c;
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 6px 10px;
          background-color: #f0f7ff;
          border-radius: 4px;
          
          .anticon {
            color: #1890ff;
          }
        }
      }
    }

    .config-section {
      width: 360px;
      flex-shrink: 0;

      .config-card {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        position: sticky;
        top: 80px;

        .card-header {
          padding: 20px 24px;
          border-bottom: 1px solid #f0f0f0;
          display: flex;
          align-items: center;
          gap: 12px;

          .anticon {
            font-size: 18px;
            color: #1890ff;
            background: linear-gradient(135deg, #e6f7ff 0%, #f0f5ff 100%);
            padding: 8px;
            border-radius: 8px;
          }

          span {
            font-size: 16px;
            font-weight: 600;
            color: #262626;
          }
        }

        .card-content {
          padding: 24px;

          .section-title {
            font-size: 14px;
            font-weight: 500;
            color: #8c8c8c;
            margin-bottom: 12px;
          }

          .upload-section {
            margin-bottom: 24px;

            .cover-uploader {
              :deep(.ant-upload) {
                width: 100% !important;
                height: 160px !important;
                background: #fafafa;
                border: 1px dashed #d9d9d9;
                border-radius: 8px;
                transition: all 0.3s;

                &:hover {
                  border-color: #40a9ff;
                  background: #e6f7ff;
                }
              }

              .upload-hint {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                height: 100%;
                color: #8c8c8c;

                .anticon {
                  font-size: 24px;
                  margin-bottom: 8px;
                  color: #1890ff;
                }

                p {
                  margin: 0 0 4px;
                  font-size: 14px;
                }

                span {
                  font-size: 12px;
                }
              }
            }
            
            .upload-status {
              margin-top: 8px;
              padding: 6px 10px;
              border-radius: 4px;
              font-size: 13px;
              display: flex;
              align-items: center;
              gap: 6px;
              
              &.uploading {
                background-color: #e6f7ff;
                color: #1890ff;
              }
              
              &.success {
                background-color: #f6ffed;
                color: #52c41a;
              }
              
              &.error {
                background-color: #fff2f0;
                color: #ff4d4f;
                justify-content: space-between;
                
                a {
                  color: #1890ff;
                  font-size: 12px;
                }
              }
            }
            
            .upload-tip {
              margin-top: 8px;
              font-size: 12px;
              color: #8c8c8c;
              display: flex;
              align-items: center;
              gap: 6px;
            }
          }

          .category-section {
            margin-bottom: 24px;

            .category-select {
              width: 100%;

              :deep(.ant-select-selector) {
                border-radius: 8px;
              }
            }
          }

          .tags-section {
            .tags-select {
              width: 100%;

              :deep(.ant-select-selector) {
                border-radius: 8px;
                padding: 4px 8px;
              }

              :deep(.ant-select-selection-item) {
                background: #f0f7ff;
                border: 1px solid #91d5ff;
                border-radius: 12px;
                color: #1890ff;
                margin: 2px;
                transition: all 0.3s;

                &:hover {
                  background: #e6f7ff;
                  transform: translateY(-1px);
                }
              }
            }

            .tags-hint {
              margin-top: 8px;
              font-size: 12px;
              color: #8c8c8c;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .create-post-container {
    .main-content {
      margin: 24px 16px;
    }
  }
}

@media (max-width: 992px) {
  .create-post-container {
    .main-content {
      flex-direction: column;

      .edit-section {
        max-width: 100%;
      }

      .config-section {
        width: 100%;

        .config-card {
          position: static;
        }
      }
    }
  }
}

@media (max-width: 576px) {
  .create-post-container {
    .page-header {
      .header-content {
        .header-left {
          h1 {
            font-size: 18px;
          }
        }

        .header-right {
          .ant-btn {
            padding: 0 12px;

            .anticon + span {
              display: none;
            }
          }
        }
      }
    }

    .main-content {
      margin: 16px 12px;

      .edit-section {
        .title-input-wrapper {
          padding: 16px;

          .title-input {
            font-size: 20px;
          }
        }

        .summary-wrapper {
          padding: 16px;
        }
      }

      .config-section {
        .config-card {
          .card-content {
            padding: 16px;
          }
        }
      }
    }
  }
}
</style>